﻿Imports Microsoft.Win32
Imports RTF
Imports System.IO
Imports iTextSharp.text.pdf

Public Class ReportBrowserForm

    Public CurrentRecord As Integer = -1
    Public LastRecord As Integer = -1
    Dim TheView As DataView
    Dim FieldsView As DataView
    Dim DTFieldsView As DataView
    Dim TheRTF As String
    Dim TheHTML As String
    Dim TheAllignment As Integer
    Dim LoadingRecords As Boolean = True
    Dim TheReportID As String

    Dim m_nFirstCharOnPage As Integer
    Dim PageNumber As Integer

    Private Sub ClostBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClostBtn.Click
        Me.Hide()

    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim strKey As String = "Software\\Microsoft\\Internet Explorer\\PageSetup"
        'Dim bolWritable As Boolean = True


        ' Dim strFooter As String = "footer"
        ' Dim FooterValue As Object = "&d"
        'Dim OldFooter As Object




        'Dim oKey As RegistryKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable)
        'If oKey IsNot Nothing Then
        'OldFooter = oKey.GetValue(strFooter)
        'oKey.SetValue(strFooter, FooterValue)
        '   oKey.SetValue(strHeader, HeaderValue)
        'Page Margins
        '   oKey.SetValue(strTop, CDbl("0.25"))
        '   oKey.SetValue(strBottom, CDbl("0.25"))
        '   oKey.SetValue(strRight, CDbl("0.25"))
        '   oKey.SetValue(strLeft, CDbl("0.25"))
        'End If


        'Browser.Print()
        'Browser.ShowPrintDialog()

        'now set the footer back
        'If oKey IsNot Nothing Then
        'oKey.SetValue(strFooter, OldFooter)
        'End If
        'oKey.Close()

        With ReportDesignerForm
            If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                .PrintDocument1.PrinterSettings.PrinterName = PrintDialog1.PrinterSettings.PrinterName
                .PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies
                .PrintDocument1.Print()
            End If
        End With




    End Sub



    Private Sub LoadRecord(ByVal RecordNum As Integer)


        If DTFieldsView.Count = 0 Then

            CurrentRecord = RecordNum
            RecordSelector.SelectedIndex = RecordNum

            If TheView.Count = 0 Then
                RTBox.Text = "No records found"
                Exit Sub
            End If

            Dim Params As New List(Of Object)
            Params.Clear()

            Params.Add(FieldsView) 'FieldsView
            Params.Add(TheView(RecordNum)) 'The record
            Params.Add(TheRTF)

            If DoSomeWork("LoadRTFReport", Params, False) = Windows.Forms.DialogResult.OK Then
                RTBox.Rtf = BusyButFine.ReturnedValues(0)
            End If

            Exit Sub
        End If

        Dim html As String
        Dim DP As Integer
        Dim RTF As String
        Dim DTRTF As String = ""
        Dim TheValue As String
        Dim ZeroText As String


        html = TheHTML
        RTF = TheRTF

        CurrentRecord = RecordNum
        RecordSelector.SelectedIndex = RecordNum
        ShowLoadingForm()
        With ReportDesignerForm



            '.RichTextBoxEx1.Text = html
            .RichTextBoxEx1.Text = RTF

            For Each r In FieldsView
                While .RichTextBoxEx1.Find("[" & r.Item("Field_Code") & "]") <> -1

                    'If IsDBNull(TheView(CurrentRecord).Item(r.Item("Field_Code"))) Then
                    '    TheValue = "0"
                    'Else
                    '    TheValue = TheView(CurrentRecord).Item(r.Item("Field_Code")).ToString
                    'End If

                    'Try
                    '    If TheValue = 0 Then
                    '        ZeroText = r.Item("Zero_Text")
                    '        TheValue = ZeroText
                    '    End If
                    'Catch ex As Exception
                    '    'keep the value as it is
                    'End Try


                    ZeroText = r.Item("Zero_Text")

                    If IsDBNull(TheView(CurrentRecord).Item(r.Item("Field_Code"))) Then
                        TheValue = "0"
                    Else
                        TheValue = TheView(CurrentRecord).Item(r.Item("Field_Code")).ToString
                    End If

                    Try
                        If TheValue = 0 Then
                            'ZeroText = GetZeroText(r.item("Field_Code"))
                            TheValue = ZeroText
                        End If
                    Catch ex As Exception
                        'keep the value as it is
                    End Try

                    DP = r.Item("Decimals")
                    If DP = -1 Then
                        .RichTextBoxEx1.SelectedText = TheValue
                    Else
                        Try
                            .RichTextBoxEx1.SelectedText = FormatNumber(TheValue, DP, TriState.True, TriState.False, TriState.True)
                        Catch ex As Exception
                            .RichTextBoxEx1.SelectedText = TheValue
                        End Try
                    End If

                    '   DP = r.Item("Decimals")
                    '   If DP = -1 Then
                    ' .RichTextBoxEx1.SelectedText = TheView(CurrentRecord).Item(r.Item("Field_Code")).ToString
                    ' Else
                    ' If IsDBNull(TheView(CurrentRecord).Item(r.Item("Field_Code"))) Then
                    ' .RichTextBoxEx1.SelectedText = "0"
                    ' Else
                    ' .RichTextBoxEx1.SelectedText = FormatNumber(TheView(CurrentRecord).Item(r.Item("Field_Code")), DP, TriState.True, TriState.False, TriState.True)
                    ' End If

                    ' End If
                End While
            Next

            'html = .RichTextBoxEx1.Text
            RTF = .RichTextBoxEx1.Text

            'html = .CalculateExpresions(html, True)
            RTF = .CalculateExpresions(RTF, False)


            .RichTextBoxEx1.Rtf = RTF

            If DTFieldsView.Count <> 0 Then
                'its a data table report


                Dim dtsql As String = ""
                Dim c As Integer
                Dim TheHeader(DTFieldsView.Count - 1) As String

                For c = 0 To DTFieldsView.Count - 1
                    TheHeader(c) = DTFieldsView(c).Item("Header").ToString
                    If dtsql = "" Then
                        dtsql = DTFieldsView(c).Item("Field_Code").ToString
                    Else
                        dtsql = dtsql & ", " & DTFieldsView(c).Item("Field_Code").ToString
                    End If
                Next

                dtsql = "Select " & dtsql & " from RD_" & Trim(TheReportID) & " where LA_Code = '" & TheView(CurrentRecord).Item("LA_Code").ToString & "' order by " & dtsql

                DTRTF = .RTFDataTable(dtsql, TheHeader)

                If DTRTF <> "" Then
                    Dim StartPos As Integer
                    Dim EndPos As Integer

                    StartPos = .RichTextBoxEx1.Find("{DTS}")
                    EndPos = .RichTextBoxEx1.Find("{DTE}")

                    If StartPos <> -1 And EndPos <> -1 Then
                        .RichTextBoxEx1.SelectionStart = StartPos
                        .RichTextBoxEx1.SelectionLength = EndPos - StartPos + 5

                        .RichTextBoxEx1.SelectedRtf = DTRTF
                    End If
                End If



                For Each r In FieldsView
                    While .RichTextBoxEx1.Find("[" & r.Item("Field_Code") & "]") <> -1

                        If IsDBNull(TheView(CurrentRecord).Item(r.Item("Field_Code"))) Then
                            TheValue = "0"
                        Else
                            TheValue = TheView(CurrentRecord).Item(r.Item("Field_Code")).ToString
                        End If

                        Try
                            If TheValue = 0 Then
                                ZeroText = r.Item("Zero_Text")
                                TheValue = ZeroText
                            End If
                        Catch ex As Exception
                            'keep the value as it is
                        End Try

                        DP = r.Item("Decimals")
                        If DP = -1 Then
                            .RichTextBoxEx1.SelectedText = TheValue
                        Else
                            Try
                                .RichTextBoxEx1.SelectedText = FormatNumber(TheValue, DP, TriState.True, TriState.False, TriState.True)
                            Catch ex As Exception
                                .RichTextBoxEx1.SelectedText = TheValue
                            End Try
                        End If

                        '   DP = r.Item("Decimals")
                        '  If DP = -1 Then
                        ' .RichTextBoxEx1.SelectedText = TheView(CurrentRecord).Item(r.Item("Field_Code")).ToString
                        'Else
                        'If IsDBNull(TheView(CurrentRecord).Item(r.Item("Field_Code"))) Then
                        ' .RichTextBoxEx1.SelectedText = "0"
                        'Else
                        '.RichTextBoxEx1.SelectedText = FormatNumber(TheView(CurrentRecord).Item(r.Item("Field_Code")), DP, TriState.True, TriState.False, TriState.True)
                        'End If

                        'End If
                    End While
                Next
            End If

            .RichTextBoxEx1.Rtf = .CalculateExpresions(.RichTextBoxEx1.Rtf, False)

            'now if it is a Data Table report, convert it back to html
            'If DTRTF <> "" Then
            '    html = .sRTF_To_HTML(.RichTextBoxEx1.Rtf)
            'End If

            If DTRTF <> "" Then
                RTF = .RichTextBoxEx1.Rtf
            End If
        End With


        'Remove some odd characters at the end of the document for some reason

        'html = html.Substring(0, html.IndexOf("</html>") + 8)
        'html = html.Replace("Ã,", "")
        'html = html.Replace("Ã", "")
        'Browser.DocumentText = html

        RTBox.Rtf = RTF

        HideLoadingForm()

    End Sub

    Public Function SaveTextToFile(ByVal strData As String, _
      ByVal FullPath As String, _
        Optional ByVal ErrInfo As String = "") As Boolean

        ' Dim Contents As String
        Dim bAns As Boolean = False
        Dim objReader As StreamWriter
        Try


            objReader = New StreamWriter(FullPath)
            objReader.Write(strData)
            objReader.Close()
            bAns = True
        Catch Ex As Exception
            ErrInfo = Ex.Message

        End Try
        Return bAns
    End Function


    Sub WordToPDF(ByVal sRTF As String, ByVal FileName As String)
        Dim MyWord As Microsoft.Office.Interop.Word.Application

        '   MessageBox.Show("Creating the Word Object")

        MyWord = CreateObject("Word.application")
        MyWord.Visible = False

        Dim TheDoc As New Microsoft.Office.Interop.Word.Document

        Try
            Kill(FileName & ".rtf")
        Catch ex As Exception

        End Try

        SaveTextToFile(sRTF, FileName & ".rtf")

        TheDoc = MyWord.Documents.Open(FileName & ".rtf")

        If TheAllignment = 0 Then
            TheDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait

        Else
            TheDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape

        End If

        TheDoc.PageSetup.LeftMargin = 20
        TheDoc.PageSetup.RightMargin = 20
        TheDoc.PageSetup.TopMargin = 5
        TheDoc.PageSetup.BottomMargin = 5

        TheDoc.ExportAsFixedFormat(FileName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False,
                                                  Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                                                  Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument,
                                                  , , Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentWithMarkup,
                                                  False, , Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks,
                                                  True, True, False)

        If Not MyWord Is Nothing Then

            Dim oDoNotSaveChanges As Object = _
             Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges
            TheDoc.Close(oDoNotSaveChanges)
            MyWord.Quit(oDoNotSaveChanges)
            MyWord = Nothing
            TheDoc = Nothing
        End If

        Try
            Kill(FileName & ".rtf")
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextBut.Click


        If CurrentRecord < LastRecord Then
            CurrentRecord = CurrentRecord + 1
            LoadRecord(CurrentRecord)

        Else
            MessageBox.Show("No more records.", "End of records set", MessageBoxButtons.OK, MessageBoxIcon.Information)

        End If
    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousBut.Click


        If CurrentRecord > 0 Then
            CurrentRecord = CurrentRecord - 1

            LoadRecord(CurrentRecord)
        Else
            MessageBox.Show("This is the first record.", "First records", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub ToolStripButton2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If System.IO.File.Exists(SaveFileDialog1.FileName) Then
                Try
                    System.IO.File.Delete(SaveFileDialog1.FileName)
                Catch ex As Exception
                    MessageBox.Show("Could not overwrite file.  The file might be read only or open by another application.", "Could not overwrite file", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End Try
            End If
            '     HTMLtoPDF(Browser.DocumentText, SaveFileDialog1.FileName)
        End If
    End Sub




    Public Sub LoadBrowserReport(ByVal ReportID As String, ByVal sql As String, ByVal html As String, ByVal RTF As String, ByVal LM As Integer, ByVal RM As Integer, ByVal TM As Integer, ByVal BM As Integer, ByVal Allignment As Integer)
        LoadingRecords = True

        TheReportID = ReportID

        TheView = LoadDataView(sql)
        FieldsView = LoadDataView("Select * from RD_Published_Report_Fields where Report_ID = '" & ReportID & "'")
        ReportDesignerForm.AllFieldsView = LoadDataView("Select * from RD_Published_Report_Fields where Report_ID = '" & ReportID & "'")
        DTFieldsView = LoadDataView("Select * from RD_Published_Datatable_Fields where Report_ID = '" & ReportID & "' order by Order_Num")

        CurrentRecord = 0

        TheHTML = html
        TheRTF = RTF
        TheAllignment = Allignment


        If TheView.Count <> 0 Then
            LoadRecordSelector()
            LastRecord = TheView.Count - 1
            With ReportDesignerForm

                .PrintDocument1.DefaultPageSettings.Landscape = Allignment
                .PrintDocument1.DefaultPageSettings.Margins.Left = LM
                .PrintDocument1.DefaultPageSettings.Margins.Right = RM
                .PrintDocument1.DefaultPageSettings.Margins.Top = TM
                .PrintDocument1.DefaultPageSettings.Margins.Bottom = BM


                .LineWidth = WYSIWYG_RTF(.RichTextBoxEx1, .PrintDocument1)

            End With

            LoadRecord(0)



        Else
            html = "No records found for the selected provider"
            '  ReportDesignerForm.RichTextBoxEx1.Text = html
            CurrentRecord = -1
            LastRecord = -1
            RecordSelector.Items.Clear()

            RTBox.Text = html

        End If

        LoadingRecords = False
    End Sub

    Private Sub LoadRecordSelector()


        If TheView.Count = 0 Then
            RecordSelector.Items.Clear()
        Else
            Dim r As DataRowView

            If DTFieldsView.Count <> 0 Then
                'load the LA's instead
                For Each r In TheView
                    RecordSelector.Items.Add(r.Item("LA_Name"))
                Next
            Else
                For Each r In TheView
                    RecordSelector.Items.Add(r.Item("Provider_Name") & " - " & r.Item("LA_Name"))
                Next
            End If

        End If



    End Sub


    Private Sub RecordSelector_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RecordSelector.SelectedIndexChanged
        If LoadingRecords = False Then
            LoadRecord(RecordSelector.SelectedIndex)
        End If
    End Sub


    Private Sub PrintMe()

        PrintDialog1.PrinterSettings.DefaultPageSettings.Margins.Left = 20
        PrintDialog1.PrinterSettings.DefaultPageSettings.Margins.Right = 20
        PrintDialog1.PrinterSettings.DefaultPageSettings.Margins.Top = 5
        PrintDialog1.PrinterSettings.DefaultPageSettings.Margins.Bottom = 5

        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

            Try
                PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings

                PrintDocument1.Print()

            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        End If


        'With ReportDesignerForm
        '    '  .RichTextBoxEx1.Rtf = RTBox.Rtf
        '    .TheReportName = Me.Text
        '    If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        '        .PrintDocument1.PrinterSettings.PrinterName = PrintDialog1.PrinterSettings.PrinterName
        '        .PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies
        '        Try
        '            .PrintDocument1.Print()
        '        Catch ex As Exception
        '            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        '        End Try


        '    End If
        'End With
    End Sub

    Private Sub ToolStripSplitButton1_ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripSplitButton1.ButtonClick

        PrintMe()


    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        PrintMe()

    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        Dim r As Integer

        If LastRecord = -1 Then Exit Sub

        With ReportDesignerForm
            If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                .PrintDocument1.PrinterSettings.PrinterName = PrintDialog1.PrinterSettings.PrinterName
                .PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies
                For r = 0 To LastRecord
                    LoadRecord(r)
                    Try
                        .PrintDocument1.Print()
                    Catch ex As Exception
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try
                Next
            End If
        End With



    End Sub

    Private Function ProviderSubCode(UPIN As Integer) As String

        Dim TheView As DataView

        TheView = LoadDataView("select provider_subtype_code from providers where upin = " & UPIN)

        If TheView.Count = 0 Then
            Return ""
        Else
            Return TheView(0).Item("provider_subtype_code")
        End If


    End Function

    Private Sub PrintBatchPDF()

        Dim FilePath, FileName As String
        'Dim UsersDeafultFolder, UsersNamingMethod, UsersMailDelivery, UsersFileExistRule, UserViewPDF As String
        Dim r As Integer
        Dim TheDate As DateTime = Now()

        If LastRecord = -1 Then Exit Sub

        FolderBrowserDialog1.Description = "Select a folder in which to save your PDF Files"
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            FilePath = FolderBrowserDialog1.SelectedPath
        Else
            FilePath = ""
        End If
        If FilePath = "" Then Exit Sub

        'TempPath = "C:\TheStore\TempFiles"

        'If Not Directory.Exists(TempPath) Then
        '    Directory.CreateDirectory(TempPath)
        'Else
        '    'delete all the files
        '    Try
        '        Kill(TempPath & "\*.*")
        '    Catch ex As Exception
        '        'kill failed
        '    End Try

        'End If

        'Change PFD Settings

        'Dim objIniFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\Destination.ini")
        'Dim objIniGenFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\General.ini")

        ''In Destination.ini
        'UsersDeafultFolder = objIniFile.GetString("Destination", "PDFName", "")
        'UsersNamingMethod = objIniFile.GetString("Destination", "NamingMode", "")
        'UsersMailDelivery = objIniFile.GetString("Destination", "bMailDelivery", "")
        'UsersFileExistRule = objIniFile.GetString("Destination", "FileExistRule", "")
        ''In General.ini
        'UserViewPDF = objIniGenFile.GetString("General", "bViewPDF", "")


        ''Overwrite with Store settings
        ''In Destination.ini
        'objIniFile.WriteString("Destination", "PDFName", TempPath & "\")
        'objIniFile.WriteString("Destination", "NamingMode", "3")
        'objIniFile.WriteString("Destination", "bMailDelivery", "0")
        'objIniFile.WriteString("Destination", "FileExistRule", "1")
        ''In General.ini
        'objIniGenFile.WriteString("General", "bViewPDF", "0")



        With ReportDesignerForm
            'Try
            '    .PrintDocument1.PrinterSettings.PrinterName = "ScanSoft PDF Create!"
            'Catch ex As Exception
            '    MessageBox.Show("Your default printer is not ScanSoft PDF Create! - The Store cannot print to PDF", "PDF Printer Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            'End Try
            '.PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies

            With ProgressBarForm
                .TheProgressBar.Minimum = 0
                .TheProgressBar.Maximum = LastRecord
                .TheProgressBar.Step = 1
                .Show()
            End With

            For r = 0 To LastRecord
                ProgressBarForm.TheProgressBar.PerformStep()

                LoadRecord(r)
                'Get and set FileName
                If DTFieldsView.Count = 0 Then
                    'its a provider

                    Dim ptypecode As String
                    Dim TerCode As String
                    Dim ptypedesc As String
                    Dim DateStr As String

                    Try
                        Select Case TheView(r).Item("Provider_Type_Code")
                            Case "Schoo"
                                ptypecode = "17"
                                ptypedesc = "s6f-" & TheView(r).Item("LA_Code")
                            Case "Acade"
                                ptypecode = "03"
                                ptypedesc = "aca"
                            Case "Local"
                                ptypecode = "18"
                                ptypedesc = "lau"
                            Case Else
                                Select Case ProviderSubCode(TheView(r).Item("UPIN"))
                                    Case "07HEP"
                                        ptypecode = "18"
                                        ptypedesc = "heo"
                                    Case Else
                                        ptypecode = "18"
                                        ptypedesc = "feo"
                                End Select
                        End Select

                       
                    Catch ex As Exception
                        'forget about it!
                        ptypecode = "00"
                        ptypedesc = "__"
                    End Try

                    DateStr = Format(TheDate, "ddMMMyy")

                    Try
                        TerCode = Mid(TheView(r).Item("Territory_Name"), 1, 2).ToString.ToLower
                    Catch ex As Exception
                        TerCode = "__"
                    End Try

                    Dim TheName As String = Me.Text

                    TheName = TheName.Replace(" ", "")
                    TheName = TheName.Replace("(", "")
                    TheName = TheName.Replace("'", "")
                    TheName = TheName.Replace("-", "")
                    TheName = TheName.Replace("&", "and")
                    TheName = TheName.Replace(",", "")
                    TheName = TheName.Replace("/", "")
                    TheName = TheName.Replace("\", "")
                    TheName = TheName.Replace(")", "")

                    TheName = Trim(TheName)

                    Dim Period = Mid(ReportsForm.PeriodBox.SelectedValue.ToString, 1, 6)

                    'FileName = "ypla-" & ptypecode & "12-" & TerCode & "-" & TheView(r).Item("UPIN") & "-" & ptypedesc & "-" & Mid(TheView(CurrentRecord).Item("Provider_Name"), 1, 10) & "_" & Period & "_" & Mid(TheName, 1, 10) & "-" & DateStr & "-v1"

                    FileName = TheView(r).Item("UPIN") & " " & ptypedesc & "-" & Mid(TheView(CurrentRecord).Item("Provider_Name"), 1, 10) & "_" & Period & "_" & Mid(TheName, 1, 10) & "-" & DateStr & "-v1"

                    'FileName = TheView(r).Item("UPIN") & " - " & TheView(CurrentRecord).Item("Provider_Name")
                Else
                    'its a LA
                    Dim FileNameBuilder As String = ""
                    Dim TerCode As String = ""

                    Try
                        TerCode = Mid(TheView(r).Item("Territory_Name"), 1, 2).ToString.ToLower
                    Catch ex As Exception
                        TerCode = "__"
                    End Try

                    Dim TheName As String = Me.Text
                    Dim DateStr As String

                    TheName = TheName.Replace(" ", "")
                    TheName = TheName.Replace("(", "")
                    TheName = TheName.Replace("'", "")
                    TheName = TheName.Replace("-", "")
                    TheName = TheName.Replace("&", "and")
                    TheName = TheName.Replace(",", "")
                    TheName = TheName.Replace("/", "")
                    TheName = TheName.Replace("\", "")
                    TheName = TheName.Replace(")", "")

                    DateStr = Format(TheDate, "ddMMMyy")

                    TheName = Trim(TheName)

                    'FileNameBuilder = "ypla-1512-" & TerCode & "-" & LAUPIN(TheView(r).Item("LA_Code")) & "-lau" & "-" & TheView(r).Item("LA_Code") & "-" & Mid(TheView(CurrentRecord).Item("LA_Name"), 1, 20) & Mid(TheName, 1, 8) & "-" & DateStr & "-v1"

                    FileNameBuilder = LAUPIN(TheView(r).Item("LA_Code")) & " lau" & "-" & TheView(r).Item("LA_Code") & "-" & Mid(TheView(CurrentRecord).Item("LA_Name"), 1, 20) & Mid(TheName, 1, 8) & "-" & DateStr & "-v1"

                    FileName = FileNameBuilder
                End If
                

                FileName = FileName.Replace("&", "and")
                FileName = FileName.Replace(".", "")

                '.PrintDocument1.DocumentName = FileName
                '.TheReportName = .PrintDocument1.DocumentName
                Try
                    '.PrintDocument1.Print()
                    WordToPDF(RTBox.Rtf, FilePath & "\" & FileName)
                Catch ex As Exception
                    MessageBox.Show("There was an error printing " & FileName & ", please try and print it individualy.  Click OK to continue. (" & ex.Message & ")", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            Next
        End With

        ProgressBarForm.Close()

        'With ProgressBarForm
        '    .TheProgressBar.Minimum = 0
        '    .TheProgressBar.Maximum = Directory.GetFiles(TempPath).Count
        '    .TheProgressBar.Step = 1
        '    .Text = "Moving files..."
        '    .Show()
        'End With

        'now copy the files over to the actual folder
        'For Each fName In Directory.GetFiles(TempPath)
        '    ProgressBarForm.TheProgressBar.PerformStep()
        '    If File.Exists(fName) Then
        '        Dim dFile As String = String.Empty
        '        dFile = Path.GetFileName(fName)
        '        Dim dFilePath As String = String.Empty
        '        dFilePath = FilePath + "\" + dFile
        '        File.Copy(fName, dFilePath, True)
        '    End If
        'Next
        'ProgressBarForm.Close()

        'Restore Users Defualt PDF Settings
        ''In Destination.ini
        'objIniFile.WriteString("Destination", "PDFName", UsersDeafultFolder)
        'objIniFile.WriteString("Destination", "NamingMode", UsersNamingMethod)
        'objIniFile.WriteString("Destination", "bMailDelivery", UsersMailDelivery)
        'objIniFile.WriteString("Destination", "FileExistRule", UsersFileExistRule)
        ''In General.ini
        'objIniGenFile.WriteString("General", "bViewPDF", UserViewPDF)

        MessageBox.Show("Your PDF Reports have printed successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End Sub

    Private Declare Sub Sleep Lib "kernel32" _
 (ByVal dwMilliseconds As Long)

    Private Sub DropZone()
        Dim FilePath, FileName, TempPath As String
        Dim UsersDeafultFolder, UsersNamingMethod, UsersMailDelivery, UsersFileExistRule, UserViewPDF As String
        Dim r As Integer

        TempPath = "C:\TheStore\TempFiles"

        If LastRecord = -1 Then Exit Sub

        FolderBrowserDialog1.Description = "Please select the location of the Drop Zone"
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            FilePath = FolderBrowserDialog1.SelectedPath
        Else
            FilePath = ""
        End If
        If FilePath = "" Then Exit Sub

        If Not Directory.Exists(TempPath) Then
            Directory.CreateDirectory(TempPath)
        Else
            'delete all the files
            Kill(TempPath & "\*.*")
        End If

        'Change PFD Settings

        Dim objIniFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\Destination.ini")
        Dim objIniGenFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\General.ini")

        'In Destination.ini
        UsersDeafultFolder = objIniFile.GetString("Destination", "PDFName", "")
        UsersNamingMethod = objIniFile.GetString("Destination", "NamingMode", "")
        UsersMailDelivery = objIniFile.GetString("Destination", "bMailDelivery", "")
        UsersFileExistRule = objIniFile.GetString("Destination", "FileExistRule", "")
        'In General.ini
        UserViewPDF = objIniGenFile.GetString("General", "bViewPDF", "")


        'Overwrite with Store settings
        'In Destination.ini
        objIniFile.WriteString("Destination", "PDFName", TempPath & "\")
        objIniFile.WriteString("Destination", "NamingMode", "3")
        objIniFile.WriteString("Destination", "bMailDelivery", "0")
        objIniFile.WriteString("Destination", "FileExistRule", "1")
        'In General.ini
        objIniGenFile.WriteString("General", "bViewPDF", "0")



        With ReportDesignerForm
            Try
                .PrintDocument1.PrinterSettings.PrinterName = "ScanSoft PDF Create!"
            Catch ex As Exception
                MessageBox.Show("Your default printer is not ScanSoft PDF Create! - The Store cannot print to PDF", "PDF Printer Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
            .PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies

            'setup the progress form

            With ProgressBarForm
                .TheProgressBar.Minimum = 0
                .TheProgressBar.Maximum = LastRecord
                .TheProgressBar.Step = 1
                .Show()
            End With

            For r = 0 To LastRecord
                ProgressBarForm.TheProgressBar.PerformStep()

                LoadRecord(r)



                Try

                    ' WritePDFProperties(FilePath & "\" & FileName)

                    'now rename the file to the correct naming convention

                    'source organisation
                    FileName = "ypla"

                    'Document Type
                    If DTFieldsView.Count = 0 Then
                        FileName = FileName & "-alc"
                    Else
                        FileName = FileName & "-sum"
                    End If

                    'Region
                    FileName = FileName & "-" & TheView(r).Item("Region_Code").ToString

                    'UPIN
                    If DTFieldsView.Count = 0 Then
                        'its a provider
                        FileName = FileName & "-" & TheView(r).Item("UPIN").ToString
                    Else
                        'its a LA
                        FileName = FileName & "-" & LAUPIN(TheView(r).Item("LA_Code").ToString).ToString
                    End If

                    'Provider Type
                    If DTFieldsView.Count = 0 Then
                        'its a provider
                        FileName = FileName & "-" & DZ_ProviderType(TheView(r).Item("UPIN").ToString)
                    Else
                        'its a LA
                        FileName = FileName & "-" & "fei"
                    End If

                    'LA_Code
                    FileName = FileName & "-" & TheView(r).Item("LA_Code").ToString

                    'Name
                    Dim TheName As String = Me.Text

                    TheName = TheName.Replace(" ", "")
                    TheName = TheName.Replace("(", "")
                    TheName = TheName.Replace("'", "")
                    TheName = TheName.Replace("-", "")
                    TheName = TheName.Replace("&", "and")
                    TheName = TheName.Replace(",", "")
                    TheName = TheName.Replace("/", "")
                    TheName = TheName.Replace("\", "")
                    TheName = TheName.Replace(")", "")

                    FileName = FileName & "-" & Trim(TheName)

                    'Date
                    FileName = FileName & "-" & Format(Now, "ddMMMyyyy")

                    'Version
                    If DTFieldsView.Count = 0 Then
                        FileName = FileName & "-v" & NextVersion(TheReportID, TheView(r).Item("RID").ToString)
                    Else
                        FileName = FileName & "-v" & NextVersion(TheReportID, LARID(TheView(r).Item("LA_Code").ToString))
                    End If

                    .PrintDocument1.DocumentName = "Report"
                    .TheReportName = .PrintDocument1.DocumentName
                    .PrintDocument1.Print()

                    'rename the file
                    If File.Exists(TempPath & "\Report.pdf") Then
                        My.Computer.FileSystem.RenameFile(TempPath & "\Report.pdf", FileName & ".pdf")
                    Else
                        'wait a 1 seconds and see if it is there
                        Sleep(1000)
                        If File.Exists(TempPath & "\Report.pdf") Then
                            My.Computer.FileSystem.RenameFile(TempPath & "\Report.pdf", FileName & ".pdf")
                        Else
                            'still not there wait one more second
                            Sleep(1000)
                            If File.Exists(TempPath & "\Report.pdf") Then
                                My.Computer.FileSystem.RenameFile(TempPath & "\Report.pdf", FileName & ".pdf")
                            End If
                        End If
                    End If


                Catch ex As Exception
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try

            Next
        End With

        ProgressBarForm.Close()

        With ProgressBarForm
            .TheProgressBar.Minimum = 0
            .TheProgressBar.Maximum = Directory.GetFiles(TempPath).Count
            .TheProgressBar.Step = 1
            .Text = "Moving files..."
            .Show()
        End With

        'now copy the files over to the actual folder
        For Each fName In Directory.GetFiles(TempPath)
            ProgressBarForm.TheProgressBar.PerformStep()
            If File.Exists(fName) Then
                Dim dFile As String = String.Empty
                dFile = Path.GetFileName(fName)
                Dim dFilePath As String = String.Empty
                dFilePath = FilePath + "\" + dFile
                File.Copy(fName, dFilePath, True)
            End If
        Next
        ProgressBarForm.Close()

        'Restore Users Defualt PDF Settings
        'In Destination.ini
        objIniFile.WriteString("Destination", "PDFName", UsersDeafultFolder)
        objIniFile.WriteString("Destination", "NamingMode", UsersNamingMethod)
        objIniFile.WriteString("Destination", "bMailDelivery", UsersMailDelivery)
        objIniFile.WriteString("Destination", "FileExistRule", UsersFileExistRule)
        'In General.ini
        objIniGenFile.WriteString("General", "bViewPDF", UserViewPDF)


        MessageBox.Show("The reports have been dropped successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub PrintPDF()

        Dim FilePath, FileName As String
        'Dim UsersDeafultFolder, UsersNamingMethod, UsersMailDelivery, UsersFileExistRule, UserViewPDF As String
        Dim r As Integer
        Dim TheDate As Date = Now()

        If LastRecord = -1 Then Exit Sub

        FolderBrowserDialog1.Description = "Select a folder in which to save your PDF Files"
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            FilePath = FolderBrowserDialog1.SelectedPath
        Else
            FilePath = ""
        End If
        If FilePath = "" Then Exit Sub

        'Change PFD Settings

        'Dim objIniFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\Destination.ini")
        'Dim objIniGenFile As New INIfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Zeon\DocuCom\PDF Driver\General.ini")

        ''In Destination.ini
        'UsersDeafultFolder = objIniFile.GetString("Destination", "PDFName", "")
        'UsersNamingMethod = objIniFile.GetString("Destination", "NamingMode", "")
        'UsersMailDelivery = objIniFile.GetString("Destination", "bMailDelivery", "")
        'UsersFileExistRule = objIniFile.GetString("Destination", "FileExistRule", "")
        ''In General.ini
        'UserViewPDF = objIniGenFile.GetString("General", "bViewPDF", "")


        ''Overwrite with Store settings
        ''In Destination.ini
        'objIniFile.WriteString("Destination", "PDFName", FilePath & "\")
        'objIniFile.WriteString("Destination", "NamingMode", "3")
        'objIniFile.WriteString("Destination", "bMailDelivery", "0")
        'objIniFile.WriteString("Destination", "FileExistRule", "1")
        ''In General.ini
        'objIniGenFile.WriteString("General", "bViewPDF", "0")



        With ReportDesignerForm
            'Try
            '    .PrintDocument1.PrinterSettings.PrinterName = "ScanSoft PDF Create!"
            'Catch ex As Exception
            '    MessageBox.Show("Your default printer is not ScanSoft PDF Create! - The Store cannot print to PDF", "PDF Printer Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            'End Try
            '.PrintDocument1.PrinterSettings.Copies = PrintDialog1.PrinterSettings.Copies
            For r = CurrentRecord To CurrentRecord
                LoadRecord(r)

                'Get and set FileName
                If DTFieldsView.Count = 0 Then
                    'its a provider

                    Dim ptypecode As String
                    Dim TerCode As String
                    Dim ptypedesc As String
                    Dim DateStr As String

                    Try
                        Select Case TheView(r).Item("Provider_Type_Code")
                            Case "Schoo"
                                ptypecode = "17"
                                ptypedesc = "s6f-" & TheView(r).Item("LA_Code")
                            Case "Acade"
                                ptypecode = "03"
                                ptypedesc = "aca"
                            Case "Local"
                                ptypecode = "15"
                                ptypedesc = "lau"
                            Case Else
                                Select Case ProviderSubCode(TheView(r).Item("UPIN"))
                                    Case "07HEP"
                                        ptypecode = "18"
                                        ptypedesc = "heo"
                                    Case Else
                                        ptypecode = "18"
                                        ptypedesc = "feo"
                                End Select
                        End Select


                    Catch ex As Exception
                        'forget about it!
                        ptypecode = "00"
                        ptypedesc = "__"
                    End Try

                    DateStr = Format(TheDate, "ddMMMyy")

                    Try
                        TerCode = Mid(TheView(r).Item("Territory_Name"), 1, 2).ToString.ToLower
                    Catch ex As Exception
                        TerCode = "__"
                    End Try

                    Dim TheName As String = Me.Text

                    TheName = TheName.Replace(" ", "")
                    TheName = TheName.Replace("(", "")
                    TheName = TheName.Replace("'", "")
                    TheName = TheName.Replace("-", "")
                    TheName = TheName.Replace("&", "and")
                    TheName = TheName.Replace(",", "")
                    TheName = TheName.Replace("/", "")
                    TheName = TheName.Replace("\", "")
                    TheName = TheName.Replace(")", "")

                    TheName = Trim(TheName)

                    Dim Period = Mid(ReportsForm.PeriodBox.SelectedValue.ToString, 1, 6)

                    'FileName = "ypla-" & ptypecode & "12-" & TerCode & "-" & TheView(r).Item("UPIN") & "-" & ptypedesc & "-" & Mid(TheView(CurrentRecord).Item("Provider_Name"), 1, 10) & "_" & Period & "_" & Mid(TheName, 1, 10) & "-" & DateStr & "-v1"

                    FileName = TheView(r).Item("UPIN") & " " & ptypedesc & "-" & Mid(TheView(CurrentRecord).Item("Provider_Name"), 1, 10) & "_" & Period & "_" & Mid(TheName, 1, 10) & "-" & DateStr & "-v1"

                    'FileName = TheView(r).Item("UPIN") & " - " & TheView(CurrentRecord).Item("Provider_Name")
                Else
                    'its a LA
                    Dim FileNameBuilder As String = ""
                    Dim TerCode As String = ""

                    Try
                        TerCode = Mid(TheView(r).Item("Territory_Name"), 1, 2).ToString.ToLower
                    Catch ex As Exception
                        TerCode = "__"
                    End Try

                    Dim TheName As String = Me.Text
                    Dim DateStr As String

                    TheName = TheName.Replace(" ", "")
                    TheName = TheName.Replace("(", "")
                    TheName = TheName.Replace("'", "")
                    TheName = TheName.Replace("-", "")
                    TheName = TheName.Replace("&", "and")
                    TheName = TheName.Replace(",", "")
                    TheName = TheName.Replace("/", "")
                    TheName = TheName.Replace("\", "")
                    TheName = TheName.Replace(")", "")

                    DateStr = Format(TheDate, "ddMMMyy")

                    TheName = Trim(TheName)

                    'FileNameBuilder = "ypla-1512-" & TerCode & "-" & LAUPIN(TheView(r).Item("LA_Code")) & "-lau" & "-" & TheView(r).Item("LA_Code") & "-" & Mid(TheView(CurrentRecord).Item("LA_Name"), 1, 20) & Mid(TheName, 1, 8) & "-" & DateStr & "-v1"

                    FileNameBuilder = LAUPIN(TheView(r).Item("LA_Code")) & " lau" & "-" & TheView(r).Item("LA_Code") & "-" & Mid(TheView(CurrentRecord).Item("LA_Name"), 1, 20) & Mid(TheName, 1, 8) & "-" & DateStr & "-v1"

                    FileName = FileNameBuilder
                End If

                

                FileName = FileName.Replace("&", "and")
                FileName = FileName.Replace(".", "")

                '.PrintDocument1.DocumentName = FileName
                '.TheReportName = .PrintDocument1.DocumentName
                Try
                    '.PrintDocument1.Print()
                    ' WritePDFProperties(FilePath & "\" & FileName)


                    WordToPDF(RTBox.Rtf, FilePath & "\" & FileName)

                Catch ex As Exception
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try

            Next
        End With

        ''Restore Users Defualt PDF Settings
        ''In Destination.ini
        'objIniFile.WriteString("Destination", "PDFName", UsersDeafultFolder)
        'objIniFile.WriteString("Destination", "NamingMode", UsersNamingMethod)
        'objIniFile.WriteString("Destination", "bMailDelivery", UsersMailDelivery)
        'objIniFile.WriteString("Destination", "FileExistRule", UsersFileExistRule)
        ''In General.ini
        'objIniGenFile.WriteString("General", "bViewPDF", UserViewPDF)


        MessageBox.Show("Your PDF Reports have printed successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End Sub

   



    Private Sub ReportBrowserForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' If CurrentUser.Level < 5 Then DropzoneBut.Visible = False Else DropzoneBut.Visible = True

        DropzoneBut.Visible = False

    End Sub

    Private Sub PDFButton_ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PDFButton.ButtonClick
        PrintPDF()

    End Sub

    Private Sub BatchPrintAllRecordsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BatchPrintAllRecordsToolStripMenuItem.Click
        PrintBatchPDF()
    End Sub

    Private Sub PrintCurrentRecordToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintCurrentRecordToolStripMenuItem.Click
        PrintPDF()
    End Sub

    Private Sub WritePDFProperties(ByVal filepath As String)
        Dim thepdfreader = New PdfReader(filepath & ".pdf")

        Dim thefile = New FileStream(filepath & "_prop.pdf", FileMode.Create, FileAccess.Write)

        Dim stamper = New PdfStamper(thepdfreader, thefile)

        Dim info = thepdfreader.Info

        info.Add("Provider_Type", "S6F")
        info.Add("Region", "GL")
        info.Add("LA", "123")
        info.Add("Business_Area", "FUNDPERFCE")

        stamper.MoreInfo = info

        thepdfreader.Close()
        stamper.Close()

        'do a quick kill and rename
        Kill(filepath & ".pdf")
        Rename(filepath & "_prop.pdf", filepath & ".pdf")

    End Sub



    Private Sub DropzoneBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropzoneBut.Click
        DropZone()

    End Sub

    Private Sub PrintDocument1_BeginPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
        ' Start at the beginning of the text
        m_nFirstCharOnPage = 0
        PageNumber = 1

    End Sub

    Private Sub PrintDocument1_EndPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.EndPrint
        ' Clean up cached information
        RTBox.FormatRangeDone()
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        ' To print the boundaries of the current page margins
        ' uncomment the next line:
        'e.Graphics.DrawRectangle(System.Drawing.Pens.Blue, e.MarginBounds)

        ' make the RichTextBoxEx calculate and render as much text as will
        ' fit on the page and remember the last character printed for the
        ' beginning of the next page


        Dim newPoint As Point = Point.Empty

        newPoint.X = e.MarginBounds.Left
        newPoint.Y = e.MarginBounds.Bottom

        ' Dim TheString As String

        ' TheString = TheReportName & " printed on " & Now().ToString

        '  e.Graphics.DrawString(TheString, System.Drawing.SystemFonts.DefaultFont, Brushes.Black, newPoint)

        m_nFirstCharOnPage = RTBox.FormatRange(False, _
                                                e, _
                                                m_nFirstCharOnPage, _
                                                RTBox.TextLength)

        ' check if there are more pages to print
        If (m_nFirstCharOnPage < RTBox.TextLength) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

        PageNumber = PageNumber + 1
        ' PrintPreviewForm.NumberofPages = PrintPreviewForm.NumberofPages + 1
        'PrintPreviewForm.PageLabel.Text = "Page 1 of " & PrintPreviewForm.NumberofPages
    End Sub
End Class